package("uspiralweb.user");

var user_details = Ext.data.Record.create([
  {name: "id", mapping:"id", type: "string"},
  {name: "uname", mapping:"uname", type: "string"},
  {name: "password", mapping:"password", type: "string"},
  {name: "email", mapping:"email", type: "string"},
  {name: "credits", mapping:"credits", type: "string"},
  {name: "lookup", mapping:"lookup", type: "string"},
  {name: "petsallowed", mapping:"petsallowed", type: "int"},
  {name: "lastseen", mapping:"lastseen", type: "string"},
  {name: "firstname", mapping:"firstname", type: "string"},
  {name: "lastname", mapping:"lastname", type: "string"},
  {name: "dateofbirth", mapping:"dateofbirth", type: "date"}]);

// only the fields for the summary list
var user_list = Ext.data.Record.create([
  {name: "id", mapping:"id", type: "string"},
  {name: "username", mapping:"username", type: "string"},
  {name: "password", mapping:"password", type: "string"},
  {name: "email", mapping:"email", type: "string"},
  {name: "credit", mapping:"credit", type: "string"},
  {name: "dateofbirth", mapping:"dateofbirth", type: "date"}]);

var obj_reader = new Ext.ux.ObjectReader({}, user_details);

//http://extjs.com/forum/showthread.php?t=18620
//function newUsersGrid()
uspiralweb.user.list = function() 
{
	//var ds;
	var grid;

  var ds_users = new Ext.ux.WriteStore({
    proxy: new Ext.data.DWRProxy(Admin.getUsers, false),
    updateProxy: new Ext.ux.DwrWriteProxy(Admin.updateUsers),
    replaceWrite: false,
    reader: new Ext.data.ListRangeReader({id:'id', totalProperty:'totalRows'}, user_list),
    remoteSort: true});

  //var ds_users = new Ext.data.Store({
  //       proxy: new Ext.data.DWRProxy(Admin.getUsers, false),
  //    sortInfo: {field:'dateofbirth', direction:'ASC'},
  //      reader: new Ext.data.ListRangeReader({id:'id', totalProperty:'totalRows'}, user_list),
  //  remoteSort: true
  //});

  var menubar = [{
      text:'Edit',
      tooltip:'Edit the user record',
      iconCls:'edit',
      handler: function(){ onRowDblClick(grid) }
  },'-',{
      text:'Add',
      tooltip:'Add a new user',
      iconCls:'addItem',
      handler: function(){ uspiralweb.user.edit(); }
  },'-',{
      text:'Delete',
      tooltip:'Remove the selected items',
      iconCls:'remove',
      handler: function(){ uspiralweb.user.remove(ds_users, grid); }
  }];

  var sm = new Ext.grid.CheckboxSelectionModel();
  grid = new Ext.grid.GridPanel({
          id: 'users_grid',
          store: ds_users,
          cm: new Ext.grid.ColumnModel([
              sm,
             {id:'id', header: 'id', width: 100, sortable: true, dataIndex: 'id'},
             {id:'username', header: 'username', width: 100, sortable: true, dataIndex: 'username'},
             {id:'password', header: 'password', width: 100, sortable: true, dataIndex: 'password'},
             {id:'email', header: 'email', width: 100, sortable: true, dataIndex: 'email'},
             {id:'credit', header: 'credit', width: 100, sortable: true, dataIndex: 'credit'},
             {id:'date', header: 'Date', width: 100, sortable: true, dataIndex: 'date'}]),
          sm: sm,
          viewConfig: {forceFit:true},
          tbar: menubar,
          bbar: new Ext.PagingToolbar({
                pageSize: 10,
                store: ds_users,
                displayInfo: true,
                displayMsg: 'Displaying messages {0} - {1} of {2}',
                emptyMsg: "No messages to display",
                 items:[]}),
          stripeRows: true,
          enableDragDrop: true,
          width: 800,
          height: 288,
          title:'Users',
          frame:true,
          iconCls:'icon-grid',
          renderTo: document.body});

  //grid.addListener('rowclick', onRowClick);
  grid.addListener('rowdblclick', onRowDblClick);
  grid.getSelectionModel().selectFirstRow();

	//ds_users.load({params:{start: 0, range: 10}, arg:[]});
  ds_users.load({params:{start:0, limit:22}, arg:['wyu', true]});			

  function onRowDblClick(grid, event)
  {
    if (!grid ||
        !grid.getSelectionModel() ||
        !grid.getSelectionModel().getSelected())
    { Ext.MessageBox.alert('Error', 'No row was selected'); return; }

    var selectionModel = grid.getSelectionModel();
    if (!event || (!event.shiftKey && !event.ctrlKey))
    { // single row selection
      var row = selectionModel.getSelected();
      if (row)
      {
        new uspiralweb.user.edit(ds_users, row.id);
        //InboxManager.getMessage(id, getMessageCallback);
      }
    }
  }
  
  return grid;
};

//function getMessageCallback(message) { Ext.getDom('preview').innerHTML = message; }
//function onRowDblClick() {}

/** adapted from the examples from Feyasoft, WYU 122907
* 
 * Copyright(c) 2006-2008, FeyaSoft Inc.
 */
/**
 * This JS is mainly used to handle action in
 * edit demo user.
 * Load data from server and assign fields in the form.
 *
 * @author fzhuang
 * @Date Oct 7, 2007
 */
//uspiralweb.user.edit = function(selectedId) {
uspiralweb.user.edit = function(ds_list, selectedId)
{
  //var User   = Ext.data.Record.create([{name: 'number'},{name: 'street'}])

  var data_store = new Ext.ux.WriteStore({
    proxy: new Ext.data.DWRProxy(Admin.getUser, false),
    updateProxy: new Ext.ux.DwrWriteProxy(Admin.setUser),
    replaceWrite: true,
    reader: obj_reader});

  // pre-define fields in the form
	var lastname  = newTextField(  'Last Name','90%','lastname');
  var firstname = newTextField(  'First Name','90%','firstname');
  var username  = newTextField(  'User Name','90%','uname');
  var password  = newPasswdField('Password','90%','password');
  var email     = newTextField(  'Email','90%','email');
  var date      = newDateField(  'Date of Birth','60%','dateofbirth');
  //var note      = newTextArea(   'note','100% -35');

    // create form panel
    var formPanel = new Ext.form.FormPanel({

        baseCls: 'x-plain',
        labelWidth: 75,
        //url:'demouser/listDemouser.htm?action=editDemouser',
        reader: obj_reader,
        //reader: new Ext.data.JsonReader({
        //    root: 'results'
        //}, ['id','username','lastname','firstname','password','email','birthday','note']
        //),
        items: [
            lastname,
            firstname,
            username,
            password,
            email,
            date]
	});

  data_store.on('load', function()
  {
	  // data loaded, do something with it here...
    lastname.setValue( data_store.getAt(0).data.lastname);
    firstname.setValue(data_store.getAt(0).data.firstname);
    username.setValue( data_store.getAt(0).data.uname);
    password.setValue( data_store.getAt(0).data.password);
    email.setValue(    data_store.getAt(0).data.email);
    date.setValue(     data_store.getAt(0).data.dateofbirth);
  });
  data_store.on('update', function()
  {
    ds_list.reload();
  });

  function submitForm()
  {
    if (formPanel.form.isValid())
    {
      if (!selectedId)
      {
        var myNewRecord = new user_details({
          lastname: lastname.getValue(),
         firstname: firstname.getValue(),
             uname: username.getValue(),
          password: password.getValue(),
             email: email.getValue(),
       dateofbirth: date.getValue()});
        
        data_store.add(myNewRecord);
      }
      else
      {
        data_store.getAt(0).data.lastname    =  lastname.getValue();
        data_store.getAt(0).data.firstname   = firstname.getValue();
        data_store.getAt(0).data.uname       =  username.getValue();
        data_store.getAt(0).data.password    =  password.getValue();
        data_store.getAt(0).data.email       =     email.getValue();
        data_store.getAt(0).data.dateofbirth =      date.getValue();
      }
      data_store.commitChanges();
      window.hide();
    }
    else
    {
      Ext.MessageBox.alert('Errors', 'Please fix the errors noted.');
    }
  }

  // load form and assign value to fields
    //formPanel.form.load({url:'demouser/listDemouser.htm?action=loadData&id='+selectedId, waitMsg:'Loading'});
    //formPanel.getForm().load();

    // define window and show it in desktop
    var window = new Ext.Window({
        title: 'Edit existing user record',
        width: 500,
        height:300,
        minWidth: 300,
        minHeight: 250,
        layout: 'fit',
        plain:true,
        bodyStyle:'padding:5px;',
        buttonAlign:'center',
        items: formPanel,

        buttons: [{text: 'Save',  handler: submitForm},
                  {text: 'Cancel',handler: function(){window.hide();}
        }]
    });

    if (selectedId) data_store.load({params:{start:0, limit:22}, arg:[selectedId]});
    //current_store = data_store;

    window.show();
};

uspiralweb.user.remove = function(dataStore, gridPanel)
{
  // get the selected items
  var m = gridPanel.getSelections();
  if(m.length > 0)
  {
  	Ext.MessageBox.confirm('Message', 'Do you really want to delete them?',
      function(btn)
      {
	      if(btn == 'yes')
		    {
			    for(var i = 0, len = m.length; i < len; i++) { dataStore.remove(m[i]); }
          dataStore.commitChanges();
          //dataStore.load({params:{start:0, limit:10}});
			  }
		  }
		);
  }
  else
  {
  	Ext.MessageBox.alert('Error', 'To process delete action, please select at least one item to continue');
  }
};